# !/usr/bin/env python
# coding:utf-8
"""
    Author = 上善若水(QQ:564667570)
    Affiliation = Institute of Subtropical Agriculture, Chinese Academy of Sciences
    Time = '2018-3-3, 11:00'
"""
#
# 1. 写一个函数计算1 + 3 + 5 +…+97 + 99 的结果
# 再写一个装饰器函数, 对其装饰, 在运算之前, 新建一个文件
# 然后结算结果, 最后把计算的结果写入到文件里

def outer(func):
    def inner(x): # use two levels of decorator to decorate the function
        file = open('yong.py', 'w', encoding='utf-8')
        print('==============')
        print('to start the calculation')
        sums = func(x) # to call the function
        print('the calculation is done!')
        file.write(str(sums))
        file.close()
        return sums
    return inner

@outer
def suma(a_list):
    sum = 0
    for num in a_list:  # to calculate the sum of a number sequence
        sum = sum + num
    return sum

# to call the function
result = suma(range(1,100,2))
print(result)


# 2.写一个函数计算传入进来参数的平方, 并将结果.写一个带参数的装饰器,
# 将装饰器参数传入到被包装的函数, 计算并输入结果
# import modules
import random
import time

# set the decorator
def Square_func_decorator(args): # the decorator with parameters
    def call_decorator(func): # in this way, we need to set triple-nesting function
        def square_decorator(*kw):
            print('Q2. the results present as following in here---------------')
            time01 = time.time()
            print('start to calculate: % s' % time01)
            square = func(*kw) * args
            time02 = time.time()
            print('the end time: % s' % time02)
            print('the calculation times: % s' % str(time02-time01))
            return square
        return square_decorator
    return call_decorator

@Square_func_decorator(random.randint(0,10)) # to call the decorator
def square_func(x):  # the decorated function
    return x**2

result = square_func(random.randint(0,100))
print(result)